import json
import re

from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from apps.areas.models import Area

from django.views.generic.base import View
from django.core.cache import cache

from apps.users.models import Address
from utils.views import LoginRequiredJSONMixin
# Create your views here.


class AreasView(View):
    def get(self, request):
        """提供省市区数据"""
        province_list = cache.get('province')
        if  province_list is None:
            # 查询省份数据
            provinces = Area.objects.filter(parent=None)

            # 序列化省级数据
            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })

            cache.set('province',province_list,24*3600)

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


class SubAreasView(View):
    """市区数据"""
    def get(self, request,id):
        """提供省市区数据"""
        # 提供市或区数据
        data_list = cache.get('city:%s'%id)
        if data_list is None:
            up_level = Area.objects.get(id=id)  # 查询市或区的父级
            down_level = up_level.subs.all()

            # 序列化市或区数据
            data_list = []
            for item in down_level:
                data_list.append({'id': item.id, 'name': item.name})

            cache.set('city:%s'%id,data_list,24*3600)
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': {'subs':data_list}})


class AddressCreateView(LoginRequiredJSONMixin,View):

    def post(self,request):
        data= json.loads(request.body.decode())
        receiver=data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        user = request.user
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code':400,'errmsg':'参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code':400,'errmsg':'参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code':400,'errmsg':'参数email有误'})

        address = Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})


class AddressView(LoginRequiredJSONMixin,View):
    """用户收货地址"""
    def get(self, request):
        # 获取所有的地址:
        user = request.user
        addresses = Address.objects.filter(user=user,is_deleted=False)
        # 创建空的列表
        address_list = []
        # 遍历
        for address in addresses:
            address_dict = ({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # return JsonResponse({'code':0,'errmsg':'ok','addresses':address_list})
        # 将默认地址移动到最前面
            default_address = user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_list.insert(0, address_dict)
            else:
                address_list.append(address_dict)

        default_id = user.default_address_id

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'addresses': address_list,
                             'default_address_id': default_id})


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息

        Address.objects.filter(id=address_id).update(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_list = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_list})

    def delete(self, request, address_id):
        """删除地址"""
        # 查询要删除的地址
        address = Address.objects.get(id=address_id)
        # 将地址逻辑删除设置为True
        address.is_deleted = True
        address.save()

        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""
    def put(self, request, address_id):
        user = request.user
        address = Address.objects.get(id=address_id)
        # 设置地址为默认地址
        user.default_address = address
        user.save()

        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """设置地址标题"""
    def put(self, request, address_id):
        data = json.loads(request.body.decode())
        title = data.get('title')

        address = Address.objects.get(id=address_id)
        # 设置新的地址标题
        address.title = title
        address.save()

        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})